package controllers

import (
	"fmt"
	"go-scripts/mysql_models"
	"go-scripts/handler"
	"errors"
)

//这个文件暂时没怎么用到，以后用到可以做修改

var userController *UserController

type UserController struct {
	userDao *mysql_models.UserDao
}
//打印用户
func (u *UserController) PrintUser(app *handler.Global) {
	app.SendJson(map[string]interface{}{
		"user": app.Request.FormValue("user"),
	})
}
//用户注册
func (u *UserController) Register(app *handler.Global)  {
	r := app.Request
	username := r.FormValue("username")
	password := r.FormValue("password")
	if username == "" || password == "" {
		app.NewError(400, errors.New("参数错误"))
	}
	userMap := map[string]interface{}{
		"username": username,
		"password": password,
	}
	users, err := u.userDao.FindByUsername(username)
	app.CheckErr(err)
	if len(users) != 0 {
		app.SendJson(map[string]interface{}{
			"message": "该用户已经注册",
		})
		return
	}
	id, err := u.userDao.Save(userMap)
	app.CheckErr(err)
	app.SendJson(map[string]interface{}{
		"message": fmt.Sprintf("save success, id is %d", id),
	})
}

func GetUserController() *UserController {
	if userController != nil {
		return userController
	}
	userController = new(UserController)
	return userController
}
//根据用户名获取用户信息
func (u *UserController) GetUser(app *handler.Global) {
	r := app.Request
	w := app.ResponseWriter
	username := r.FormValue("username")
	if username == "" {
		HandleError(w, r, "username cannot be null string", 400)
	}
	users, err := u.userDao.FindByUsername(username)
	if err != nil {
		HandleError(w, r, "查询错误", 500)
		return
	}
	SendJson(w, users)
}